package com.ruoyi.business.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;


import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.business.dao.CustomerClassDao;
import org.apache.commons.lang3.StringUtils;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.business.dao.CustomerDao;
import com.ruoyi.common.core.domain.entity.Customer;
import com.ruoyi.business.service.ICustomerService;
import com.ruoyi.framework.web.service.TokenService;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

/**
 * CustomerService业务层处理
 *
 * @author liutietou
 * @since 1.0 2025-06-27
 */
@Transactional(readOnly = true)
@Service
public class CustomerServiceImpl implements ICustomerService {

    @Autowired
    private CustomerDao customerDao;
    @Autowired
    private TokenService tokenService;
    /**
     * 查询Customer
     *
     * @param ccuscode CustomerID
     * @return Customer
     */
    @Override
    public Customer findById(String ccuscode) {
        return customerDao.findById(ccuscode).get();
    }

    /**
     * 分页查询Customer列表
     *
     * @param req Customer
     * @return Customer
     */
    @Override
    public Page<Customer> findCustomerPage(Customer req) {
        Specification<Customer> example = formatQueryParams(req);
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Pageable pageable = PageRequest.of(pageDomain.getPageNo(),
                Optional.ofNullable(pageDomain.getPageSize()).orElse(PageDomain.DEFAULT_PAGE_SIZE),
                Sort.Direction.DESC,
                Optional.ofNullable(pageDomain.getOrderByColumn()).orElse("ccuscode"));
        Page<Customer> page = customerDao.findAll(example, pageable);
        return page;
    }


    @Override
    public List<Customer> findCustomer(Customer req) {
        Specification<Customer> example = formatQueryParams(req);
        List<Customer> list = customerDao.findAll(example);
        return list;
    }

    /**
     * 分页查询Customer列表
     *
     * @param req Customer
     * @return Customer
     */
    @Override
    public List<Customer> findCustomerList(Customer req) {
        Specification<Customer> example = formatQueryParams(req);
        List<Customer> list = customerDao.findAll(example, Sort.by(Sort.Direction.DESC,"createTime"));
        return list;
    }

    private Specification<Customer> formatQueryParams(Customer req){
        Specification<Customer> example = new Specification<Customer>() {
            private static final long serialVersionUID = 1L;
            SysUser sysUser=    tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
            @Override
            public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> list = new ArrayList<>();
                if (StringUtils.isNotBlank(req.getCcuscode())){
                    Predicate pre = cb.equal(root.get("ccuscode").as(String.class), req.getCcuscode());
                    list.add(pre);
                }
                if (StringUtils.isNotBlank(req.getCcusname())){
                    Predicate pre = cb.like(root.get("ccusname").as(String.class), "%" + req.getCcusname()+ "%");
                    list.add(pre);
                }
                if(!sysUser.isAdmin() && null!=sysUser.getCust()){
                    Predicate pre = cb.equal(root.get("ccuscode").as(String.class),  sysUser.getCust().getCcuscode());
                    list.add(pre);
                }

                if (StringUtils.isNotBlank(req.getCcccode())){
                    Predicate pre = cb.like (root.get("ccccode").as(String.class),  req.getCcccode()+"%");
                    list.add(pre);
                }

                if (list.isEmpty()) {
                    return null;
                }
                return cb.and(list.toArray(new Predicate[0]));
            }
        };
        return example;
    }

    /**
     * 保存（新增/修改）Customer
     *
     * @param customer Customer
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void save(Customer customer) {
        customerDao.save(customer);
    }


    /**
     * 批量删除Customer
     *
     * @param ccuscodes 需要删除的CustomerID
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteByIds(List<String> ccuscodes) {
        List<Customer> existBeans = customerDao.findAllById(ccuscodes);
        if(!existBeans.isEmpty()){
            customerDao.deleteAll(existBeans);
        }
    }

    /**
     * 删除Customer信息
     *
     * @param ccuscode CustomerID
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteCustomerById(String ccuscode) {
         customerDao.deleteById(ccuscode);
    }



}
